import React, { Component } from 'react'
import {
  Form,
  Input,
  Radio,
  Button,
  Select,
  message,
  Spin,
  InputNumber,
} from 'antd'
import _ from 'lodash'
import Title from '@/components/Title'
import getData from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import { inject } from 'mobx-react/index'
import AuthComponent from '@/components/AuthComponent'

import './index.less'

import regexp from '@/Utils/regexp'

const { Option } = Select
const { addLeauge, getOrgTypeList } = address.fabric
const { checkDomain } = address.common

@AuthComponent('fabric-league-create')
@inject('SocketModel')
export default class CreateLeague extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // 初始值
      con_expiration: 1,
      initialValues: {
        con_consensus: 'raft',
        con_region: 'cn-huhehaote',
        con_expiration: 1,
        gsjz: 'Kafka',
        adress: 'shanghai',
        isGuomi: 0,
        version: '1.4.6',
      },
      // 右边当前选中值
      currentValues: {
        con_name: '',
        con_domain: '',
        con_consensus: 'raft',
        con_region: '呼和浩特',
        con_orderers: '',
        con_peers: '',
        con_description: '',
        con_expiration: 1,
        totalPrice: '',
        isGuomi: 0,
        version: '1.4.6',
      },
      orderOrgArr: [],
      peerOrgArr: [],
      loading: false,
    }
  }
  formRef = React.createRef();

  getPeer = async(type, setstateKey, error = '获取orderer组织列表失败') => {
    let res = await getData().get(getOrgTypeList.format({ orgType: type }))
    if (res && res.status === 200) {
      this.setState({
        [setstateKey]: res.data,
      })
    } else {
      message.error(error)
    }
  };
  componentDidMount() {
    this.getPeer('orderer', 'orderOrgArr')
    this.getPeer('peer', 'peerOrgArr', '获取peer组织列表失败')
  }

  resetArr = (e) => {
    // 重置为默认值
    this.formRef.current.resetFields(['con_orderers', 'con_peers'])
    this.setState({
      currentValues: {
        ...this.state.currentValues,
        con_orderers: '',
        con_peers: '',
        isGuomi: e.target.value,
      },
    })
  };

  // 数据提交
  onFinish = async() => {
    let values = this.formRef.current.getFieldsValue()
    let con_peers = values.con_peers || []
    values.con_peers = con_peers.length
      ? con_peers.map((element) => {
        return element.value
      })
      : []
    values.con_orderers = values.con_orderers.map((element) => {
      return element.value
    })
    values.con_vote_strategy = values.con_vote_strategy.toString()
    values.isGuomi = !!values.isGuomi
    this.setState({
      loading: true,
    })
    let res = await getData().post(addLeauge, values)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      message.success('联盟创建中...')
      this.props.history.push({
        pathname: '/dashboard/fabric',
      })
    } else if (res && res.status === 409) {
      message.error('联盟名称已存在！')
    } else {
      message.error(_.get(res, 'message') || _.get(res, 'error') || '创建联盟失败')
    }
  };
  // 点击提交按钮触发真实的数据提交
  onSubmit = () => {
    this.formRef.current.submit()
  };
  onChange = (values) => {
    let currentValues = {
      ...this.state.currentValues,
      ...values,
    }
    this.setState({
      currentValues,
    })
  };
  // 跳转创建组织页面
  goToCreateOrg = (path) => {
    this.props.history.push({
      pathname: path,
    })
  };

  // // 验证组织购买时长和联盟购买时长关系，组织购买时长 >= 联盟购买时长
  // validator = (rule, value, type) => {
  //   let message = ''
  //   if (type === 'orderOrgArr') {
  //     message = '请选择有效时长大于联盟有效时长的orderer组织'
  //   } else if (type === 'peerOrgArr') {
  //     message = '请选择有效时长大于联盟有效时长的peer组织'
  //   }

  //   if (value) {
  //     const selectedExpiration = this.formRef.current.getFieldValue(
  //       'con_expiration'
  //     )
  //     let flag = true
  //     value.forEach((item) => {
  //       const data = this.state[type]
  //       for (let i = 0, len = data.length; i < len; i++) {
  //         if (item.value === data[i].id) {
  //           if (Number(data[i].expiration) < selectedExpiration) {
  //             flag = false
  //           }
  //         }
  //       }
  //     })
  //     if (flag) {
  //       return Promise.resolve()
  //     } else {
  //       return Promise.reject(message)
  //     }
  //   } else {
  //     return Promise.reject()
  //   }
  // };

  createOrg = () => {
    // message.warn("暂无接口支持该功能")
  };

  render() {
    const {
      initialValues,
      currentValues,
      orderOrgArr,
      peerOrgArr,
      loading,
    } = this.state
    const formObj = this.formRef.current
    return (
      <div className="common fabric-create-org fabric-create-league">
        <Spin spinning={loading}>
          {/* <TabsList> */}
          {/* <div className="tabs-wrapper">
              <Title title="填写配置" />
              <div>
                <Form
                  className="create-form"
                  initialValues={initialValues}
                  onFinish={this.createOrg}
                  onValuesChange={(changedValues, allValues) =>
                    this.onChange(changedValues)
                  }
                  onChange={() => this.forceUpdate()}
                  ref={(ref) => (this.form = ref)}
                  onFinishFailed={this.onFinishFailed}
                >
                  <Form.Item
                    name="org_name"
                    label="联盟名称"
                    className="form-item"
                    help="请输入联盟名称，最多输入20字符"
                    rules={[
                      { required: true, message: "请输入联盟名称！" },
                    ]}
                  >
                    <Input
                      placeholder="请输入"
                      className="input"
                      maxLength={20}
                      autoComplete="off"
                    />
                  </Form.Item>
                  <Form.Item
                    name="org_domain"
                    label="联盟域名"
                    className="form-item"
                    help="请填写正确的联盟域名，最多输入32个字符"
                    rules={[
                      { required: true, message: "请输入联盟域名" },
                      ({ getFieldValue }) => ({
                        validator(rule, value) {
                          if (value) {
                            if (!regexp.url.test(value)) {
                              return Promise.reject("请输入正确的域名");
                            }
                            if (/[_]/g.test(value)) {
                              return Promise.reject("请输入正确的域名");
                            }
                            return Promise.resolve();
                          } else {
                            return Promise.resolve();
                          }
                        },
                      }),
                    ]}
                  >
                    <Input
                      placeholder="请输入"
                      className="input"
                      autoComplete="off"
                      maxLength={32}
                    />
                  </Form.Item>
                  <Form.Item
                    className="form-item"
                    label="共识机制"
                    name="gsjz"
                    rules={[
                      { required: true, message: '请选择共识机制' }
                    ]}
                  >
                    <Radio.Group >
                      <Radio.Button value="Kafka">Kafka</Radio.Button>
                      <Radio.Button value="Raft">Raft</Radio.Button>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    className="form-item"
                    label="地域"
                    name="adress"
                  >
                    <Radio.Group >
                      <Radio.Button value="shanghai">上海</Radio.Button>
                      <Radio.Button value="wuhan">武汉</Radio.Button>
                      <Radio.Button value="beijing">北京</Radio.Button>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    className="form-item"
                    label='投票策略'
                    name='con_vote_strategy'
                    rules={[
                      { required: true, message: '请输入投票策略' },
                      { type: 'number', pattern: /^d+$/, min: 0, max: 100, message: '请输入0-100的整数' }
                    ]}
                  >
                    <InputNumber /> <span className="percent">%</span>
                  </Form.Item >

                  <div className="diver" />

                  <Form.Item
                    // label="Peer/Orderer节点："
                    label="网络服务"
                    style={{ textTransform: "capitalize" }}
                  >
                    <Peer
                      form={this.form}
                      isShowDelete={false}
                      flag="network"
                      getForm={() => {
                        return this.form;
                      }}
                      onChange={(key, list) => {
                        this.setState({
                          [key]: list,
                        });
                      }}
                    />
                  </Form.Item>
                  <Form.Item>
                    <div className="peer-check">
                      * 网络服务信息填写完成后，点击右侧按钮，进行检测
                                        <Button type="primary" onClick={() => { this.peerCheckFn() }}>开始检测</Button>
                    </div>
                  </Form.Item>

                  <Form.Item>
                    <Button htmlType="submit" className="submit com-normal-btn com-btn-primary">
                      提&nbsp;交
                                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div> */}
          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
            <div className="tabs-wrapper">
              <div className="league-config-info config-info">
                <Title title="填写配置" />
                <Form
                  className="create-form "
                  ref={this.formRef}
                  initialValues={initialValues}
                  onFinish={this.onFinish}
                  onValuesChange={this.onChange}
                >
                  <Form.Item
                    name="version"
                    label="版本"
                    className="form-item"
                    // help="* 2.2.1不支持国密算法"
                  >
                    <Radio.Group>
                      <Radio.Button value="1.4.6">1.4.6</Radio.Button>
                      {/* <Radio.Button disabled={formObj && formObj.getFieldValue('isGuomi') === 1} value="2.2.1">2.2.1</Radio.Button> */}
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    name="con_name"
                    label="联盟名称"
                    className="form-item"
                    help="请输入联盟名称，最多输入20字符"
                    rules={[{ required: true, message: '请输入联盟名称' }]}
                  >
                    <Input
                      placeholder="请输入联盟名称"
                      style={{ width: '320px' }}
                      maxLength={20}
                      className="input"
                    />
                  </Form.Item>
                  <Form.Item
                    name="con_domain"
                    label="联盟域名"
                    className="form-item"
                    validateFirst
                    validateTrigger="onBlur"
                    rules={[
                      { required: true, message: '请输入联盟域名' },
                      () => ({
                        validator(rule, value = '') {
                          if (!regexp.url.test(value) || /[_A-Z]/g.test(value)) {
                            return Promise.reject('请输入正确的域名')
                          }
                          return Promise.resolve()
                        },
                      }),
                      {
                        validator: (_, value) => {
                          return new Promise(async(resolve, reject) => {
                            const { status, data = {}} = await getData().get(checkDomain.format({ domain: value }))
                            if (status === 200 && data.exist) {
                              reject('该域名已被使用')
                            } else {
                              resolve()
                            }
                          })
                        },
                      },
                    ]}
                  >
                    <Input
                      placeholder="请输入联盟域名"
                      maxLength={32}
                      className="input"
                      style={{ width: '320px' }}
                    />
                  </Form.Item>
                  <Form.Item
                    name="con_consensus"
                    label="共识机制"
                    className="form-item"
                  >
                    <Radio.Group>
                      <Radio.Button value="raft">Raft</Radio.Button>
                    </Radio.Group>
                  </Form.Item>
                  {/* <Form.Item
                    name="con_region"
                    label="地域"
                    className="form-item"
                  >
                    <Radio.Group>
                      <Radio.Button value="cn-huhehaote">呼和浩特</Radio.Button>
                    </Radio.Group>
                  </Form.Item> */}
                  <Form.Item name="isGuomi" label="国密算法">
                    <Radio.Group onChange={this.resetArr}>
                      <Radio value={1} disabled={(formObj && formObj.getFieldValue('version') === '2.2.1')}>是</Radio>
                      <Radio value={0}>否</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    className="form-item vote-item"
                    label="投票策略"
                    name="con_vote_strategy"
                    rules={[
                      { required: true, message: '请输入投票策略' },
                      {
                        type: 'number',
                        min: 0,
                        max: 100,
                        message: '请输入0-100的整数',
                      },
                    ]}
                  >
                    <InputNumber />
                  </Form.Item>
                  <div className="diver"></div>
                  <Form.Item
                    label={<div className="common-select">选择Orderer组织</div>}
                    className="form-item form-item-required"
                  >
                    <Form.Item
                      name="con_orderers"
                      noStyle
                      // dependencies={['con_expiration']}
                      rules={[
                        { required: true, message: '请选择Orderer组织！' },
                        // {
                        //   validator: (rule, value) =>
                        //     this.validator(rule, value, 'orderOrgArr'),
                        // },
                      ]}
                    >
                      <Select
                        mode="multiple"
                        labelInValue
                        style={{ width: 320 }}
                        placeholder="请选择Orderer组织"
                      >
                        {orderOrgArr
                          .filter((v) => v.isGuomi === currentValues.isGuomi)
                          .map((item) => {
                            return (
                              <Option key={item.id}>
                                {item.display_name || '无'}
                              </Option>
                            )
                          })}
                      </Select>
                    </Form.Item>
                    <span
                      className="create-org-text"
                      onClick={() =>
                        this.goToCreateOrg(
                          '/dashboard/fabric/createOrganization'
                        )
                      }
                    >
                      构建组织
                    </span>
                  </Form.Item>
                  <Form.Item
                    name="con_peers"
                    label="选择Peer组织"
                    className="form-item"
                    // dependencies={['con_expiration']}
                  >
                    <Select
                      mode="multiple"
                      labelInValue
                      style={{ width: 320 }}
                      placeholder="请选择Peer组织"
                    >
                      {peerOrgArr
                        .filter((v) => v.isGuomi === currentValues.isGuomi)
                        .map((item) => {
                          return (
                            <Option key={item.id}>
                              {item.display_name || '无'}
                            </Option>
                          )
                        })}
                    </Select>
                  </Form.Item>
                  <Form.Item
                    name="con_description"
                    label="描述"
                    className="form-item"
                  >
                    <Input.TextArea
                      placeholder="请输入描述，最多输入250字符"
                      className="description"
                      maxLength={250}
                      autoComplete="off"
                    />
                  </Form.Item>
                  {/* <Form.Item
                    name="con_expiration"
                    label="购买时长"
                    className="form-item"
                  >
                    <Radio.Group>
                      <Radio.Button value={1}>一个月</Radio.Button>
                      <Radio.Button value={6}>半年</Radio.Button>
                      <Radio.Button value={12}>一年</Radio.Button>
                    </Radio.Group>
                  </Form.Item> */}
                  <Form.Item className="form-item" label=" ">
                    <Button type="primary" onClick={this.onSubmit}>
                      确认
                    </Button>
                    <Button
                      style={{ marginLeft: '12px' }}
                      onClick={() => this.props.history.goBack()}
                    >
                      取消
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
            {/* <div className="current-info league-current-info ">
              <Title title='当前配置' />
              <div className="info">
                <div className="item-info">
                  <span className="item-text">联盟名称</span>
                  <span className="item-value">{currentValues.con_name || "-"}</span>
                </div>
                <div className="item-info">
                  <span className="item-text">联盟域名</span>
                  <span className="item-value">{currentValues.con_domain || "-"}</span>
                </div>
                <div className="item-info">
                  <span className="item-text">共识机制</span>
                  <span className="item-value" style={{ textTransform: "capitalize" }}>{currentValues.con_consensus}</span>
                </div>
                <div className="item-info">
                  <span className="item-text">地域</span>
                  <span className="item-value">{currentValues.con_region}</span>
                </div>
                <div className="item-info">
                  <span className="item-text">支持国密算法</span>
                  <span className="item-value">
                    {currentValues.isGuomi ? '支持' : '不支持'}
                  </span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">Orderer组织</span>

                  <span className="item-value">{
                    Array.isArray(currentValues.con_orderers) ?
                      currentValues.con_orderers.map(element => {
                        return element.label
                      }).join("、")
                      :
                      "-"
                  }</span>
                </div>
                <div className="item-info">
                  <span className="item-text">Peer组织</span>
                  <span className="item-value">{
                    Array.isArray(currentValues.con_peers) ?
                      currentValues.con_peers.map(element => {
                        return element.label
                      }).join("、")
                      :
                      "-"
                  }</span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">购买时长</span>
                  <span className="item-value">{expiration[currentValues.con_expiration]}</span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">配置费用</span>
                  <span className="item-value"><span className="symbol">¥</span>11988.00</span>
                </div>
              </div>
              <div className="btn">
                <Button className="buy-btn" onClick={this.onSubmit}>立即购买</Button>
              </div>
            </div> */}
          </div>
          {/* </TabsList> */}
        </Spin>
      </div>
    )
  }
}
